const app = getApp()
const db = wx.cloud.database()
const _ = db.command
const $ = db.command.aggregate
const to = app.require("lib/awaitTo")
const { addMessage } = app.require("utils/request/message")
const loginCheck = app.require("utils/loginCheck")

module.exports = {
    data: {
        follow: {
            flag: false,
            loading: false
        }
    },
    async getFollow() {
        // 获取关注的用户
        const res = await db.collection("user").aggregate()
            .project({
                isFollow: $.in([this.data.me._id || '', '$fans']),
            })
            .match({
                _id: this.data.userId,
            })
            .end()

        if (res.list[0].isFollow) {
            this.setData({ "follow.flag": true })
        }
    },
    async follow() {
        // 关注（取消关注）用户
        if (await loginCheck()) { return }
        this.setData({
            "follow.loading": true
        })
        const [err] = await to(db.collection("user")
            .doc(this.data.userId)
            .update({
                data: {
                    fans: this.data.follow.flag ? _.pull(this.data.me._id) : _.push(this.data.me._id),
                    fansNum: _.inc(this.data.follow.flag ? -1 : 1)
                }
            }), "follow")
        this.setData({
            "follow.loading": false
        })
        if (err) return
        if (!this.data.follow.flag) { addMessage({ type: "follow", _receiverId: this.data.userId }) }
        this.setData({
            "follow.flag": !this.data.follow.flag
        })
    }
}